import React from 'react';
import Tloader from 'react-touch-loader';
import './tab.css';
import axios from 'axios';
import { Item,Icon,Button,Modal,TextArea } from 'semantic-ui-react';
class QuestionModel extends React.Component {
  // props 传入组件的方式要看组件是以类来定义的还是以函数的形式定义的
  constructor(props) {
    super(props);
    this.state = {
      size: 'small',
      commentStyle: {
        width: '100%',
        border: 0
      },
      value:''//为表单控件TextArea做成受控组件提供的数据
    };
  }
  handleSbumit=()=>{
    axios.post('infos/question',{
      question: this.state.value
    }).then(result=>{
      // if(result.meta.status === 200) {
        this.props.close()
      // }
    })
  }
  handleChange=(e)=>{
    this.setState({
      value:e.target.value
    })
  }
  render() {
    return (
      <div> 
        <Modal open={this.props.open} size={this.state.size}> 
          <Modal.Header>发表评论</Modal.Header>
          <Modal.Content>
            <TextArea value={this.state.value} onChange={this.handleChange} style={this.state.commentStyle} placeholder='Tell us more' />
          </Modal.Content>
          <Modal.Actions>
            <Button negative onClick={this.props.close}>取消</Button>
            <Button positive icon='checkmark' onClick={this.handleSbumit} labelPosition='right' content='发表' />
          </Modal.Actions>
        </Modal>
      </div>
    )
  }
}
const RecoMessage = (props) => {
    // 组件在当前页面中被使用的话通过传参的形式来接收 props就是属性的集合 而this.props是实例组件被调用传入的属性的集合
    let content = [];
    props.listData.forEach(item=>{
      content.push(
        <Item key={item.id}>
          <Item.Image size='small' src='http://localhost:8086/public/1.png' />
          <Item.Content verticalAlign='middle'>
            <Item.Header className='info-title'>{item.info_title}</Item.Header>
            <Item.Meta>
              <span className='price'>$1200</span>
              <span className='stay'>1 Month</span>
            </Item.Meta>
          </Item.Content>
        </Item>
      );
    })
    return (
      <Item.Group unstackable>
        {content}
      </Item.Group>
    );
  }
  const AskAnswer = (props) => {
    // 尽量以类的形式来定义组件
    let list = [];
    props.listData.forEach(item=>{
      list.push(
        <li key={item.question_id}>
          <div className='title'>
            <span className='cate'>
              <Icon color='green' name='users' size='small' />
              思维
            </span>
            <span>
              {item.question_name}
            </span>
          </div>
          {item.answer_content&&(
            <div className='user'>
              <Icon circular name='users' size='mini'/>
              {item.username} 的回答
            </div>
          )}
          <div className="info">
            {item.answer_content}
          </div>
          <div className="tag">
            {item.question_tag&&item.question_tag.split(',').map((tag,index)=>{return <span key={index}>{tag}X</span>})}
            <span>{item.qnum?item.qnum:0}个回答</span>
          </div>
        </li>
      );
    });
    return (
      <div>
        <QuestionModel close={props.close} open={props.open}/>
        <div className='info-ask-btn'>
          <Button onClick={props.close} fluid color='green'>快速提问</Button>
        </div>
        <ul className='info-ask-list'>{list}</ul>
      </div>
    );
  }
  
class Loader extends React.Component{
    constructor(props) {
        super(props);
        this.state = { 
            initializing: 0,
            hasMore: true, // 默认有更多是数据
            listData: [],
            total: 0,
            pagenum: 0, // 从第几条数据开始请求
            pagesize: 2, // 请求几条
            loadEnd:false, // 提供一个状态来控制重复刷新（跟防表单重复提交类似）
            open:false
        }
      }
    refresh = (resolve, reject) => {
        if(this.state.loadEnd){
          return reject()
        } 
        setTimeout(() => { //refresh和loadMore这两个回调函数中要操作this.state上的数据的逻辑组件要求放入异步队列里面（可能refresh和loadMore被调用的时候this.state上的数据没有及时跟新）
          this.setState({
               pagenum:0,
               loadEnd:true  //请求没回来的时候一直是true，所以刷新调用refresh一直被return
             });
            this.loadData().then((result)=>{
                this.setState({
                    listData:result,
                    loadEnd:false              
                  });
                  resolve()
            })
        }, 0);
        // resolve() 调用方法结束刷新
    }
    loadMore = (resolve) => {
        // 点击加载更多
        setTimeout(() => {
            this.setState({ // this.state.pagenum=this.state.pagenum+this.state.pagesize这样直接操作也行但是推荐使用this.setState来进行操作，不然数据类型复杂的可能会出现问题
                pagenum:this.state.pagenum+this.state.pagesize,
              });
              this.loadData().then((result)=>{
                var newArray=[...this.state.listData, ...result]
                this.setState({
                    listData:newArray,
                    hasMore:this.state.pagenum >0 && this.state.pagenum < this.state.total // 在每次点击的时候来判断是否还有更多的数据            
                  });
                  resolve() //数据跟新停止刷新样式
              })
        }, 0);
    }
    loadData = () => {
        const {type} = this.props;
        return axios.post('infos/list',{
          pagenum: this.state.pagenum,
          pagesize: this.state.pagesize,
          type: type
        }).then(result=>{
          if(result.meta.status === 200) {
            this.setState({
              total: result.data.list.total
            });
          }
          return result.data.list.data
        })
      }
      handleClose = ()=>{
        this.setState({
          open:!this.state.open
        })
      }
      initList = () => {
        // 产生列表内容
        const {type} = this.props;
        if(type === 1 || type === 2) {
          // 加载资讯
          return <RecoMessage listData={this.state.listData}/>
        }else if(type === 3){
          // 加载问答列表
          return <AskAnswer listData={this.state.listData} close={this.handleClose} open={this.state.open}/>
        }
      }
      componentDidMount(){
        this.loadData().then((result)=>{
            this.setState({
              listData:result
            })
        })
      }
    render(){
        const {
            hasMore, initializing
          } = this.state;
        return(// 每个组件（return）都需要一个根元素
        <div className="view"> 
            <Tloader className="main"
            onRefresh={(resolve, reject) => this.refresh(resolve, reject)}
            onLoadMore={(resolve) => this.loadMore(resolve)}
            hasMore={hasMore}
            initializing={initializing}>
            <ul>{this.initList()}</ul>
            </Tloader>
        </div>
        )
    }
} 
export default Loader
